<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Model\Admin;

use App\Exception\BusinessException;

/**
 * 字典相关.
 */
class Dict
{
    /**
     * 获取字典
     * @param string $name
     * @return mixed|null
     */
    public static function get(string $name)
    {
        $value = Option::where('name', static::dictNameToOptionName($name))->value('value');
        return $value ? json_decode($value, true) : null;
    }

    /**
     * 保存字典.
     * @param string $name
     * @param mixed $values
     * @throws BusinessException
     */
    public static function save(string $name, mixed $values): void
    {
        if (! preg_match('/[a-zA-Z]/', $name)) {
            throw new BusinessException(1,'字典名只能包含字母');
        }
        $option_name = static::dictNameToOptionName($name);
        if (! $option = Option::where('name', $option_name)->first()) {
            $option = new Option();
        }
        $format_values = static::filterValue($values);
        $option->name = $option_name;
        $option->value = json_encode($format_values, JSON_UNESCAPED_UNICODE);
        //$option->created_by = admin_id();
        $option->save();
    }

    /**
     * 删除字典.
     */
    public static function delete(array $names): void
    {
        foreach ($names as $index => $name) {
            $names[$index] = static::dictNameToOptionName($name);
        }
        Option::whereIn('name', $names)->delete();
    }

    /**
     * 字典名到option名转换.
     */
    public static function dictNameToOptionName(string $name): string
    {
        return "dict_{$name}";
    }

    /**
     * option名到字典名转换.
     */
    public static function optionNameToDictName(string $name): string
    {
        return substr($name, 5);
    }

    /**
     * 过滤值
     * @throws BusinessException
     */
    public static function filterValue(array $values): array
    {
        $format_values = [];
        foreach ($values as $item) {
            if (! isset($item['value']) || ! isset($item['name'])) {
                throw new BusinessException(1, '字典格式错误');
            }
            $format_values[] = ['value' => $item['value'], 'name' => $item['name']];
        }
        return $format_values;
    }
}
